package com.zihan.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.zihan.constant.JwtClaimsConstant;
import com.zihan.constant.ParamsConstant;
import com.zihan.constant.UserConstant;
import com.zihan.context.UserContext;
import com.zihan.domain.dto.UserDTO;
import com.zihan.domain.entity.User;
import com.zihan.domain.result.PageResult;
import com.zihan.domain.result.Result;
import com.zihan.domain.vo.UserVO;
import com.zihan.properties.JwtProperties;
import com.zihan.service.IUserService;
import com.zihan.utils.AccountLockUtil;
import com.zihan.utils.JwtUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zhangzihan
 * @since 2025-10-17
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private AccountLockUtil accountLockUtil;
    @Resource
    private IUserService userService;
    @Resource
    private JwtProperties jwtProperties;
    // 用户登录
    @PostMapping("/login")
    public Result<String> login(@RequestBody User user) {
        // 1. 检查账户是否被锁定
        Long lockTime = accountLockUtil.accountIsLocked(user.getAccount());
        if (lockTime != null && lockTime > 0) {
            return Result.error("账户已被锁定，请" + lockTime + "秒后再试");
        }

        User res = userService.lambdaQuery()
                .eq(User::getAccount, user.getAccount())
                .eq(User::getPassword, DigestUtil.md5Hex(user.getPassword().getBytes(StandardCharsets.UTF_8)))
                .one();

        if (res == null) {
            // 3. 登录失败，记录失败次数
            accountLockUtil.lockAccount(user.getAccount());
            return Result.error(UserConstant.USER_LOGIN_ERROR);
        }

        if (res.getStatus() == 2) {
            return Result.error(UserConstant.USER_ACCOUNT_PROHIBIT);
        }

        // 4. 登录成功，重置失败计数
        accountLockUtil.unlockAccount(user.getAccount());

        // 设置ThreadLocal中的用户ID (用于后续请求)
        UserContext.setCurrentId(res.getId());

        // 用户登录成功，下发令牌 token （用户身份信息）
        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID, res.getId());
        map.put(JwtClaimsConstant.USER_NAME, res.getUsername());
        map.put(JwtClaimsConstant.USER_ACCOUNT, res.getAccount());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), map);
        // 返回前端token令牌
        return Result.success(token);
    }


    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public Result<UserVO> info() {
        Long userId = UserContext.getCurrentId();
        User user = userService.getById(userId);
        UserVO userVO = new UserVO();
        String roleName = getRoleName(user.getRoleId());
        userVO.setRole(roleName);
        BeanUtil.copyProperties(user,userVO);
        return Result.success(userVO);
    }




    /**
     * 退出登录
     */
    @PutMapping("/logout")
    public Result<String> logout() {
        UserContext.removeCurrentId();
        return Result.success();
    }


    /**
     * 获取用户列表信息
     */
    @GetMapping("/list")
    public Result<PageResult> list(UserDTO userDTO) {
        return userService.getList(userDTO);
    }


    /**
     * 重置用户密码
     */
    @PutMapping("/resetPassword/{id}")
    public Result<String> resetPassword(@PathVariable Long id) {
        return userService.resetPassword(id);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        return userService.register(user);
    }


    /**
     * 修改用户用户启用或者禁用
     */
    @PutMapping("/updateStatus/{status}/{userId}")
    public Result<String> updateStatus(@PathVariable Integer status,@PathVariable Long userId) {
//        Long userId = UserContext.getCurrentId();
        if (Objects.isNull(status)) {
            return Result.error(ParamsConstant.LACK_PARAMS);
        }
        // 修改用户状态启用或者禁用 1启用 2禁用
        User user = new User();
        user.setId(userId);
        user.setStatus(status);
        return userService.updateById(user) ? Result.success(UserConstant.USER_STATUS_SUCCESS) : Result.error(UserConstant.USER_STATUS_ERROR);
    }


    /**
     * 审批用户
     */
    @PutMapping("/approval/{userId}")
    public Result<String> approval(@PathVariable Long userId) {
        if (Objects.isNull(userId)) {
            return Result.error(ParamsConstant.LACK_PARAMS);
        }
        // 查询用户
        User user = userService.getById(userId);
        if (Objects.isNull(user)) {
            return Result.error(UserConstant.USER_NOT_EXIST);
        }
        if (!UserConstant.USER_0.equals(user.getStatus())) {
            return Result.error(UserConstant.USER_HAS_APPROVED);
        }
        // 更新用户状态，为0时才能更新 审批通过
        user.setStatus(UserConstant.USER_1);
        userService.updateById(user);
        return Result.success(UserConstant.USER_STATUS_SUCCESS);
    }


    // 查询所有教师用户
    @GetMapping("teachers")
    public Result<List<UserVO>> getAllTeachers() {
        List<User> list = userService.lambdaQuery()
                .eq(User::getRoleId, UserConstant.USER_2)
                .eq(User::getStatus, 1)
                .list();

        List<UserVO> res = list.stream().map(u -> {
            UserVO userVO = new UserVO();
            BeanUtil.copyProperties(u, userVO);
            return userVO;
        }).collect(Collectors.toList());
        return Result.success(res);
    }


    // 获取所有的学生信息
    @GetMapping("/students/list")
    public Result<List<UserVO>> getAllStudents(String name) {

        List<User> list = userService.lambdaQuery()
                .eq(User::getRoleId, 3)
                .eq(User::getStatus, 1)
                .and(StrUtil.isNotBlank(name), wrapper -> wrapper
                        .like(User::getUsername, name)
                        .or()
                        .like(User::getAccount, name)
                )
                .list();
        List<UserVO> res = list.stream().map(u -> {
            UserVO userVO = new UserVO();
            BeanUtil.copyProperties(u, userVO);
            return userVO;
        }).collect(Collectors.toList());
        return Result.success(res);
    }


    // 更新密码
    @PutMapping("/updatePassword")
    public Result<String> updatePassword(@RequestBody UserDTO user) {
        return userService.updatePassword(user);
    }


    @PutMapping("/updateInfo")
    public Result<String> updateInfo(@RequestBody UserDTO user) {
        Long userId = UserContext.getCurrentId();
        User user1 = userService.getById(userId);
        if (Objects.isNull(user1)) {
            return Result.error(UserConstant.USER_NOT_EXIST);
        }
        BeanUtil.copyProperties(user,user1);
        userService.updateById(user1);
        return Result.success("更新成功");
    }

    public String getRoleName(Long roleId) {
        switch (roleId.intValue()) {
            case 1:
                return "admin";
            case 2:
                return "teacher";
            case 3:
                return "student";
            default:
                return "未知";
        }
    }
}
